package bean

import "sync"

type DefaultBeanContext struct {
	rwmutex *sync.RWMutex
	beans   map[string]interface{}
}

func NewDefaultBeanContext() *DefaultBeanContext {
	it := new(DefaultBeanContext)
	it.init()
	return it
}

func (me *DefaultBeanContext) init() {
	me.rwmutex = new(sync.RWMutex)
	me.beans = make(map[string]interface{})
}

func (me *DefaultBeanContext) All() []interface{} {
	me.rwmutex.RLock()
	defer me.rwmutex.RUnlock()

	all := make([]interface{}, len(me.beans))
	i := 0
	for _, v := range me.beans {
		all[i] = v
		i++
	}
	return all
}

func (me *DefaultBeanContext) Set(name string, obj interface{}) {
	me.rwmutex.Lock()
	defer me.rwmutex.Unlock()

	me.beans[name] = obj
}

func (me *DefaultBeanContext) Get(name string) interface{} {
	me.rwmutex.RLock()
	defer me.rwmutex.RUnlock()

	it, ok := me.beans[name]
	if ok {
		return it
	} else {
		return nil
	}
}
